﻿using System.Collections.Generic;
using stunnware.CRM.Fetch;
using System.Linq;
using System;

namespace LinqtoCRM
{
    internal static class StunnwareExtensions
    {
        public static bool HasSelectedAttributes(this FetchEntityBase e)
        {
            return e.Columns.AllColumns || e.Columns.Columns.Count > 0;
        }

        private static IEnumerable<FetchEntityBase> EntityAndChilds(FetchEntityBase e)
        {
            yield return e;
            foreach (FetchEntityBase linked in e.LinkEntities)
            {
                foreach (FetchEntityBase child in EntityAndChilds(linked))
                {
                    yield return child;
                }
            }
        }

        public static IEnumerable<FetchEntityBase> GetEntities(this FetchStatement stmt)
        {
            if (stmt.Entity == null)
            {
                throw new ArgumentNullException("stmt", "stmt.Entity can't be null");
            }
            foreach(FetchEntityBase e in EntityAndChilds(stmt.Entity))
            {
                yield return e;
            }
        }

        public static FetchEntityBase GetEntity(this FetchStatement stmt, string name)
        {
            try
            {
                return stmt.GetEntities().Single(e => e.EntityName == name);
            }
            catch (InvalidOperationException)
            {
                return null;
            }
        }

        public static bool SingleCondition(this FetchFilter f)
        {
            return f.Filters.Count == 0 && f.Conditions.Count == 1;
        }
    }
}
